<?php
//随机获取订单编号
function build_order_no()
{
    /* 选择一个随机的方案 */
    //mt_srand((double) microtime() * 1000000);
    return date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

//获取幸运号
function get_number($array,$num){
    $array=explode(',',$array);
    shuffle($array);
    $number = implode(',', array_slice($array,0,$num));
    $new_array = implode(',',array_splice($array, $num));
    $result['new_array'] = $new_array;
    $result['number'] =$number;
    return $result;
}

function gtTime($time_s,$time_n){
    $strtime = '';
    $time = $time_n-$time_s;
    if($time >= 86400){
        return $strtime = date('Y-m-d H:i:s',$time_s);
    }
    if($time >= 3600){
        $strtime .= intval($time/3600).'小时';
        $time = $time % 3600;
    }else{
        $strtime .= '';
    }
    if($time >= 60){
        $strtime .= intval($time/60).'分钟';
        $time = $time % 60;
    }else{
        $strtime .= '';
    }
    if($time > 0){
        $strtime .= intval($time).'秒前';
    }else{
        $strtime = "时间错误";
    }
    return $strtime;
}

//function time_left($start_time,$end_time){
//    $time = $end_time-$start_time;
//    $strtime = '';
//    if($time >= 86400){
//        return round($time / 86400).'天'.date('H:i:s',$time % 86400);
//    }else if(3600 < $time && $time < 86400){
//        return date('H:i:s',$time);
//    }else if($time >= 60){
//        $strtime .= intval($time/60).'分钟';
//        $time = $time % 60;
//    }else{
//        $strtime .= '';
//    }
//    if($time > 0){
//        $strtime .= intval($time).'秒';
//    }
//    return $strtime;
//}
function time_left($start_time,$end_time){
    $time = $end_time-$start_time;
    if ($time > 0) {
        $day = floor($time / (60 * 60 * 24));
        $hour = floor($time / (60 * 60)) - ($day * 24);
        $minute = floor($time / 60) - ($day * 24 * 60) - ($hour * 60);
        $second = floor($time) - ($day * 24 * 60 * 60) - ($hour * 60 * 60) - ($minute * 60);
    }else{
        return '';
    }
    if ($minute <= 9) $minute = '0' .$minute;
    if ($second <= 9) $second = '0' .$second;
    $timeStr = '';
    if($day > 0){
        $timeStr .=$day.'天 ';
    }
    if($hour >0){
        $timeStr .=$hour.':';
    }
    if($minute >0){
        $timeStr .=$minute.':';
    }else{
        $timeStr .='00:';
    }
    if($second >0){
        $timeStr .=$second;
    }else{
        $timeStr .='00';
    }
    return $timeStr;
}

function get_kaijiang()
{
    $url = 'http://chart.cp.360.cn/zst/qkj/?lotId=255401';
    $content = file_get_contents($url);
    $result = json_decode($content);
    //var_dump($result->$x->WinNumber);
    return $result;


}
function  check_time($time){
    $flag = 0;
    for($j=0; $j<strlen($time); $j++)
    {
        if(substr($time, $j, 1) == '0')
            continue;
        else {
            $time = substr($time, $j);
            $flag = 1;
            break;
        }
    }
    if($flag == 0)
        $time = 0;
    return $time;
}
function get_time($timestamp)
{
//    $x =  intval(date('YmdHis', $timestamp));
   // $x =  date('YmdHis', $timestamp);
    $x =  date('His', $timestamp);
    return $x;
}


function check_id($kid)
{
    if(!is_numeric($kid))
        $this->error('不要传非法参数');

    $kid = intval($kid);

    return $kid;
}

/**
 * 多个数组的笛卡尔积
 *
 */
function combineDika() {
    $data = func_get_args();
    $data = current($data);
    $cnt = count($data);
    $result = array();
    $arr1 = array_shift($data);
    foreach($arr1 as $key=>$item)
    {
        $result[] = array($item);
    }

    foreach($data as $key=>$item)
    {
        $result = combineArray($result,$item);
    }
    return $result;
}

/**
 * 两个数组的笛卡尔积
 * @param $arr1
 * @param  $arr2
 */
function combineArray($arr1,$arr2) {
    $result = array();
    foreach ($arr1 as $item1)
    {
        foreach ($arr2 as $item2)
        {
            $temp = $item1;
            $temp[] = $item2;
            $result[] = $temp;
        }
    }
    return $result;
}

function match_chinese($chars,$encoding='utf8')
{
    $pattern =($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u':'/[\x80-\xFF]/';
    preg_match_all($pattern,$chars,$result);
    $temp =join('',$result[0]);
    return $temp;
}

function get_ip(){
    $realip = '';
    $unknown = 'unknown';
    if (isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach($arr as $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                    break;
                }
            }
        }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
            $realip = $_SERVER['REMOTE_ADDR'];
        }else{
            $realip = $unknown;
        }
    }else{
        if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
            $realip = getenv("HTTP_CLIENT_IP");
        }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
            $realip = getenv("REMOTE_ADDR");
        }else{
            $realip = $unknown;
        }
    }
    $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
    return $realip;
}

function get_ip_lookup($ip = ''){
    if(empty($ip)){
        $ip = get_ip();
    }
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json['ret']) && $json['ret'] == 1){
        $json['ip'] = $ip;
        unset($json['ret']);
    }else{
        return false;
    }
    return $json;
}

/**
 * 生产随机字符串
 * @param int $length 长度
 * @return string 随机字符串
 */
function get_rand_code($length = 16)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randCode = '';
    for ($i = 0; $i < $length; $i++) {
        $randCode .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $randCode;
}
/**
 * 生产随机数字
 * @param int $length 长度
 * @return string 随机数字
 */
function get_rand_number($length = 16)
{
    $chars = '0123456789';
    $randCode = '';
    for ($i = 0; $i < $length; $i++) {
        $randCode .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $randCode;
}

/**
 * 验证手机号是否正确
 * @param $mobile
 * @return 是否为手机号
 */
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[\d]{9}$|^18[\d]{9}$#', $mobile) ? true : false;
}

/**
 * 验证身份证是否正确
 * @param $idcard 身份证
 * @return bool 是否正确
 */
function check_id_card($idcard){
    // 只能是18位
    if(strlen($idcard)!=18){
        return false;
    }
    // 取出本体码
    $idcard_base = substr($idcard, 0, 17);

    // 取出校验码
    $verify_code = substr($idcard, 17, 1);

    // 加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);

    // 校验码对应值
    $verify_code_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');

    // 根据前17位计算校验码
    $total = 0;
    for($i=0; $i<17; $i++){
        $total += substr($idcard_base, $i, 1)*$factor[$i];
    }

    // 取模
    $mod = $total % 11;

    // 比较校验码
    if($verify_code == $verify_code_list[$mod]){
        return true;
    }else{
        return false;
    }
}

function idcard_verify_number($idcard_base){
    if (strlen($idcard_base) != 17){ return false; }
    // 加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);

    // 校验码对应值
    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');

    $checksum = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++){
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }

    $mod = strtoupper($checksum % 11);
    $verify_number = $verify_number_list[$mod];

    return $verify_number;
}


// 将15位身份证升级到18位
function idcard_15to18($idcard){
    if (strlen($idcard) != 15){
        return false;
    }else{
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false){
            $idcard = substr($idcard, 0, 6) . '18'. substr($idcard, 6, 9);
        }else{
            $idcard = substr($idcard, 0, 6) . '19'. substr($idcard, 6, 9);
        }
    }

    $idcard = $idcard . idcard_verify_number($idcard);

    return $idcard;
}

//18位身份证校验码有效性检查
function idcard_checksum18($idcard){
    if (strlen($idcard) != 18){ return false; }
    $aCity = array(11 => "北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",
        21=>"辽宁",22=>"吉林",23=>"黑龙江",
        31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",
        41=>"河南",42=>"湖北",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",
        50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏",
        61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",
        71=>"台湾",81=>"香港",82=>"澳门",
        91=>"国外");
    //非法地区
    if (!array_key_exists(substr($idcard,0,2),$aCity)) {
        return false;
    }
    //验证生日
    if (!checkdate(substr($idcard,10,2),substr($idcard,12,2),substr($idcard,6,4))) {
        return false;
    }
    $idcard_base = substr($idcard, 0, 17);
    if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))){
        return false;
    }else{
        return true;
    }
}
function check_bank_card($no){
    $arr_no = str_split($no);
    $last_n = $arr_no[count($arr_no)-1];
    krsort($arr_no);
    $i = 1;
    $total = 0;
    foreach ($arr_no as $n){
        if($i%2==0){
            $ix = $n*2;
            if($ix>=10){
                $nx = 1 + ($ix % 10);
                $total += $nx;
            }else{
                $total += $ix;
            }
        }else{
            $total += $n;
        }
        $i++;
    }
    $total -= $last_n;
    $total *= 9;
    if($last_n == ($total%10)){
        return true;
    }else{
        return false;
    }
}

function controller_flock($file){
    $fp = fopen($file, 'w+');
    flock($fp,LOCK_EX);
    return $fp;
}

function controller_unflock($fp)
{
    flock($fp, LOCK_UN);
    fclose($fp);
}